#include <stdio.h>
#include <stdlib.h>
#include <math.h>

//prototype function calcAvg
double calcAvg(const int n, const double p[]);
//prototype function calcVar
double calcVar(const int n, const double p[]);

//function main 
int main(int argc, char **argv){
  //declare local variables
  const int size = 10;
  double *dataArray;
  double mean, variance;
  int i;

  //allocate memory for dataArray
  dataArray = (double*)malloc(size * sizeof(double));

  //if memory fail to be allocated exit main function returning 1
  if(dataArray == NULL)
    exit(1);  

  //set dataArray elements 
  dataArray[0] = 10.0;
  dataArray[1] = 20.0;
  dataArray[2] = 15.0;
  dataArray[3] = 75.0;
  dataArray[4] = 130.;
  dataArray[5] = 45.0;
  dataArray[6] = 22.0;
  dataArray[7] = 55.0;
  dataArray[8] = 78.0;
  dataArray[9] = 8.0;

  //print data array
  printf("Data array:");
  for(i=0; i<size; i++){
    printf("%.2lf ", dataArray[i]); 
  }
  printf("\n");

  //calculate Arithmetic mean
  mean = calcAvg(size, dataArray);
  //calculate variance
  variance = calcVar(size, dataArray);

  //print Arithmetic mean  
  printf("Arithmetic mean: %.4lf\n", mean);
  //print variance
  printf("Variance: %.4lf\n", variance);

  //free allocated memory
  free(dataArray);

  //exit main function returning 0
  return 0;
}

//function calcAvg
double calcAvg(const int n, const double p[]){
  double sum = 0;
  int i;
  
  //calculate sum of array elements
  for(i=0; i<n; i++){
    sum = sum + p[i];
  }
  
  //test if n is 0 to avoid dividing by 0
  if(n==0)
    return 0;
  else	
    return sum/n; //return Arithmetic mean
}

//function calcVar
double calcVar(const int n, const double p[]){
  double mean, sum = 0;
  int i;
  
  //calculate Arithmetic mean
  mean = calcAvg(n, p);
  
  //for each array element:
  // calculate the difference between the array element and the mean
  // then calculate the power of 2 of the result
  // the result is then added to variable sum   
  for(i=0; i<n; i++){
    sum = sum + pow((p[i] - mean), 2.0);
  }

  //test if n is 0 to avoid dividing by 0 
  if(n==0)
    return 0;
  else	
    return sum/n;  //return variance
}


